#include "drv_tim_basic.h"
#include "drv_sysclk.h"
#include "drv_led.h"
#include <mm32f327xx_hal_config.h>

TIM_BASIC_Init_Type htim;

void Drv_TIM_Basic_Init(void)
{
    /* Set the counter counting step. */
    TIM_CLK_EN();
    htim.ClockFreqHz = HAL_GetSysClockFreq();
    htim.StepFreqHz = 1000; /* set the step. */
    htim.Period = 1000 - 1u; /* set the period. */
    htim.EnablePreloadPeriod = false;
    htim.PeriodMode = TIM_BASIC_PeriodMode_Continuous;  /* continus mode */
    TIM_BASIC_Init(TIM_PORT, &htim);

    /* Enable interrupt. */
    NVIC_EnableIRQ(TIM_IRQn);
    TIM_BASIC_EnableInterrupts(TIM_PORT, TIM_BASIC_INT_UPDATE_PERIOD, true);

    /* Start the counter. */
    TIM_BASIC_Start(TIM_PORT);
}

void TIM_IRQHandler(void)
{
    static volatile LED_Status status = off;
    uint32_t flags = TIM_BASIC_GetInterruptStatus(TIM_PORT);
    if ( 0u != (flags & TIM_BASIC_STATUS_UPDATE_PERIOD ) )
    {  
        status = !status;
        BOARD_LED(status);
    }
    TIM_BASIC_ClearInterruptStatus(TIM_PORT, flags);
}
